package com.qf.zyh.util;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    private static SqlSessionFactory sf;
    private static final ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();
    static {
        try {
            InputStream rs = Resources.getResourceAsStream("mybatis-config.xml");
            sf = new SqlSessionFactoryBuilder().build(rs);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static  SqlSession getsession(){
        SqlSession session = THREAD_LOCAL.get();
        if (session==null) {
            session = sf.openSession();
            THREAD_LOCAL.set(session);
        }
        return session;
    }

    public static void close(){
        SqlSession session = getsession();
        session.close();
        THREAD_LOCAL.remove();
    }
    public static void commit(){
        SqlSession session = getsession();
        session.commit();
        close();
    }
    public static void rollback(){
        SqlSession session = getsession();
        session.rollback();
        close();
    }

    public static <T extends Object> T getMapper(Class<T> tClass){
        SqlSession session = getsession();
        return session.getMapper(tClass);
    }
}
